package com.remoter.cluster.internal;

import java.util.List;
import java.util.Random;

import com.remoter.api.cluster.support.AbstractLoadBalance;
import com.remoter.api.context.support.Exporter;
import com.remoter.api.context.support.Importer;
import com.remoter.api.extension.annotation.ExtensionName;

@ExtensionName("random")
public class RandomLoadBalance extends AbstractLoadBalance{
	
	private final Random random = new Random(); 
	
	@Override
	public Exporter doSelect(Importer importer,List<Exporter> exporters){
		int length = exporters.size();
		int totalWeight = 0;
		boolean sameWeight = true;
		for(int i=0;i<length;i++){
			int weight = this.getWeight(exporters.get(i));
			totalWeight += weight;
			if(sameWeight && i>0 && weight != this.getWeight(exporters.get(i-1))){
				sameWeight = false;
			}
		}
		if(totalWeight > 0 && !sameWeight){
			int offset = random.nextInt(totalWeight);
			for(int i=0;i<length;i++){
				offset -= this.getWeight(exporters.get(i));
				if(offset < 0){
					return exporters.get(i);
				}
			}
		}
		return exporters.get(random.nextInt(length));
	}
	
}